<template>
	<div class="favorites-page" :class="'app-container theme-' + getCurrentTheme()">
		<!-- 自定义导航栏 -->
		<div class="custom-nav-bar">
			<div class="nav-left" @click="goBack">
				<div class="back-btn">
					<text class="back-icon">←</text>
					<text class="back-text">返回</text>
				</div>
			</div>
			<div class="nav-title">我的收藏</div>
			<div class="nav-right">
				<!-- 调试按钮 -->
				<div class="debug-btn" @click="showDebugInfo">
					<text class="debug-text">🔍</text>
				</div>
			</div>
		</div>
		
		<div class="favorites-content">
			<div class="favorites-list" v-if="favoriteChats.length > 0">
				<div 
					class="favorite-item"
					v-for="chat in favoriteChats" 
					:key="chat.id"
					@click="openChat(chat)"
				>
					<div class="favorite-icon-wrapper">
						<div class="chat-avatar">
							<text class="avatar-text">💬</text>
						</div>
					</div>
					<div class="favorite-content">
						<div class="favorite-header">
							<div class="favorite-title">{{ chat.title || '未命名对话' }}</div>
							<div class="favorite-badge">收藏</div>
						</div>
						<div class="favorite-preview">{{ chat.lastMessage || '暂无消息' }}</div>
						<div class="favorite-footer">
							<div class="favorite-time">{{ formatTime(chat.updatedAt) }}</div>
							<div class="continue-chat">点击继续对话 →</div>
						</div>
					</div>
					<div class="favorite-actions">
						<div class="unfavorite-btn" @click.stop="toggleFavorite(chat)">
							<text class="unfavorite-icon">💔</text>
						</div>
					</div>
				</div>
			</div>
			
			<div class="empty-favorites" v-else>
				<div class="empty-icon-wrapper">
					<div class="empty-icon">⭐</div>
					<div class="empty-shine"></div>
				</div>
				<div class="empty-text">还没有收藏的对话</div>
				<div class="empty-action" @click="goBack">
					<text class="action-text">去收藏对话</text>
					<text class="action-arrow">→</text>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import chatApi from '@/api/chat.js'

export default {
	data() {
		return {
			favoriteChats: []
		}
	},
	onLoad() {
		this.loadFavoriteChats()
	},
	onShow() {
		this.loadFavoriteChats()
	},
	methods: {
		goBack() {
			// 确保返回到首页
			uni.navigateBack({
				delta: 1,
				fail: () => {
					// 如果返回失败，直接跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			})
		},
		
		async loadFavoriteChats() {
			try {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				const token = uni.getStorageSync('token')
				
				if (!userInfo || !userInfo.id || !token) {
					this.favoriteChats = []
					return
				}
				
				// 从后端获取用户收藏的对话
				const response = await chatApi.getUserCollectedConversations(userInfo.id)
				
				// 后端直接返回数组，不是包装在data字段中
				const conversations = Array.isArray(response) ? response : []
				
				this.favoriteChats = conversations.map(conv => ({
					id: conv.id,
					title: conv.title || '未命名对话',
					lastMessage: conv.preview || conv.lastMessage || '暂无消息',
					updatedAt: conv.updatedAt || conv.createdAt,
					messageCount: conv.messageCount || 0,
					originalItem: conv // 保留原始数据
				}))
			} catch (error) {
				console.error('从后端加载收藏对话失败:', error)
				
				// 后备方案：从本地存储获取
				try {
					const favorites = uni.getStorageSync('favorites') || []
					
					// 过滤出对话收藏（区别于消息收藏）
					const conversationFavorites = favorites.filter(item => item.isConversation)
					
					this.favoriteChats = conversationFavorites.map(item => ({
						id: item.conversationId,
						title: item.title,
						lastMessage: item.preview || item.content,
						updatedAt: item.createdAt,
						originalItem: item // 保留原始数据用于删除
					}))
					
				} catch (e) {
					console.error('加载本地收藏对话也失败:', e)
					this.favoriteChats = []
				}
			}
		},
		
		openChat(chat) {
			// 检查chatId是否有效
			if (!chat.id) {
				console.error('对话ID无效:', chat);
				uni.showToast({
					title: '对话ID无效',
					icon: 'none'
				});
				return;
			}
			
			// 显示加载提示
			uni.showLoading({
				title: '加载对话中...'
			});
			
			// 使用reLaunch确保回到主页面，并传递chatId参数
			uni.reLaunch({
				url: `/pages/index/index?chatId=${chat.id}`,
				success: () => {
					uni.hideLoading();
				},
				fail: (err) => {
					console.error('跳转失败:', err);
					uni.hideLoading();
					uni.showToast({
						title: '跳转失败',
						icon: 'error'
					});
					
					// 备用方案：直接返回主页面
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}, 1000);
				}
			});
		},
		
		async toggleFavorite(chat) {
			try {
				// 显示确认对话框
				const res = await new Promise((resolve) => {
					uni.showModal({
						title: '确认取消收藏',
						content: '确定要取消收藏这个对话吗？',
						showCancel: true,
						cancelText: '取消',
						confirmText: '确定',
						confirmColor: '#ff4444',
						success: resolve
					});
				});
				
				if (!res.confirm) {
					return; // 用户取消操作
				}
				
				// 调用后端API取消收藏
				await chatApi.setCollectConversation(chat.id, false)
				
				// 重新加载收藏列表
				await this.loadFavoriteChats()
				
				uni.showToast({
					title: '已取消收藏',
					icon: 'success'
				})
			} catch (error) {
				console.error('取消收藏失败:', error)
				
				// 后备方案：从本地存储移除
				try {
					let favorites = uni.getStorageSync('favorites') || []
					// 根据conversationId删除对应的收藏项
					favorites = favorites.filter(item => item.conversationId !== chat.id)
					uni.setStorageSync('favorites', favorites)
					
					// 更新本地数据
					this.loadFavoriteChats()
					
					uni.showToast({
						title: '已取消收藏(本地)',
						icon: 'success'
					})
				} catch (e) {
					console.error('本地取消收藏也失败:', e)
					uni.showToast({
						title: '操作失败',
						icon: 'error'
					})
				}
			}
		},
		
		getCurrentTheme() {
			return uni.getStorageSync('selectedTheme') || 'light'
		},
		
		showDebugInfo() {
			const favorites = uni.getStorageSync('favorites') || []
			const chatHistory = uni.getStorageSync('chatHistory') || []
			
			console.log('=== 调试信息 ===');
			console.log('收藏数据:', favorites);
			console.log('聊天历史:', chatHistory);
			console.log('当前收藏对话:', this.favoriteChats);
			
			uni.showModal({
				title: '调试信息',
				content: `收藏总数: ${favorites.length}\n对话收藏: ${this.favoriteChats.length}\n聊天历史: ${chatHistory.length}`,
				showCancel: false
			});
		},
		
		formatTime(timestamp) {
			if (!timestamp) return ''
			
			const now = new Date()
			const date = new Date(timestamp)
			const diff = now - date
			
			if (diff < 60000) {
				return '刚刚'
			} else if (diff < 3600000) {
				return Math.floor(diff / 60000) + '分钟前'
			} else if (diff < 86400000) {
				return Math.floor(diff / 3600000) + '小时前'
			} else if (diff < 2592000000) {
				return Math.floor(diff / 86400000) + '天前'
			} else {
				return date.getMonth() + 1 + '月' + date.getDate() + '日'
			}
		}
	}
}
</script>

<style scoped>
.favorites-page {
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	flex-direction: column;
}

/* 自定义导航栏样式 */
.custom-nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 32rpx;
	padding-top: calc(24rpx + var(--status-bar-height, 44rpx));
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(20rpx);
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
	position: sticky;
	top: 0;
	z-index: 100;
}

.nav-left,
.nav-right {
	flex: 1;
	display: flex;
	align-items: center;
}

.nav-right {
	justify-content: flex-end;
}

.debug-btn {
	padding: 12rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
	transition: all 0.2s ease;
	cursor: pointer;
}

.debug-btn:hover {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(1.1);
}

.debug-text {
	font-size: 28rpx;
}

.app-container.theme-light .debug-btn {
	background: rgba(0, 0, 0, 0.1);
}

.app-container.theme-light .debug-btn:hover {
	background: rgba(0, 0, 0, 0.15);
}

.back-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 12rpx 20rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50rpx;
	transition: all 0.2s ease;
	cursor: pointer;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.back-btn:hover {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(1.05);
}

.back-icon {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
}

.back-text {
	font-size: 28rpx;
	font-weight: 600;
	color: #ffffff;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
}

.nav-title {
	flex: 2;
	text-align: center;
	font-size: 36rpx;
	font-weight: 700;
	color: #ffffff;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

/* 明亮主题导航栏 */
.app-container.theme-light .custom-nav-bar {
	background: rgba(255, 255, 255, 0.95);
	border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
}

.app-container.theme-light .back-btn {
	background: rgba(0, 0, 0, 0.05);
	border: 1rpx solid rgba(0, 0, 0, 0.1);
}

.app-container.theme-light .back-btn:hover {
	background: rgba(0, 0, 0, 0.1);
}

.app-container.theme-light .back-icon,
.app-container.theme-light .back-text {
	color: #1f2937;
	text-shadow: none;
}

.app-container.theme-light .nav-title {
	color: #1f2937;
	text-shadow: none;
}

/* 明亮主题 */
.app-container.theme-light .favorites-page {
	background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

/* 深色主题 */
.app-container.theme-dark .favorites-page {
	background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
}

/* 紫色主题 */
.app-container.theme-purple .favorites-page {
	background: linear-gradient(135deg, #2d1b69 0%, #5b21b6 100%);
}

/* 蓝色主题 */
.app-container.theme-blue .favorites-page {
	background: linear-gradient(135deg, #1e3a8a 0%, #3730a3 100%);
}

.favorites-content {
	flex: 1;
	padding: 32rpx 24rpx;
}

.favorites-list {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.favorite-item {
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(20rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.2);
	border-radius: 20rpx;
	padding: 32rpx;
	display: flex;
	align-items: flex-start;
	gap: 24rpx;
	transition: all 0.3s ease;
	cursor: pointer;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	position: relative;
	overflow: hidden;
}

.favorite-item::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 4rpx;
	background: linear-gradient(90deg, #8b5cf6 0%, #06b6d4 50%, #10b981 100%);
	opacity: 0;
	transition: opacity 0.3s ease;
}

.favorite-item:hover::before {
	opacity: 1;
}

.app-container.theme-light .favorite-item {
	background: rgba(255, 255, 255, 0.95);
	border: 1rpx solid rgba(0, 0, 0, 0.08);
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.favorite-item:hover {
	transform: translateY(-4rpx);
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
	background: rgba(255, 255, 255, 0.15);
}

.app-container.theme-light .favorite-item:hover {
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
	background: rgba(255, 255, 255, 1);
}

.favorite-icon-wrapper {
	flex-shrink: 0;
}

.chat-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #8b5cf6 0%, #06b6d4 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 12rpx rgba(139, 92, 246, 0.3);
}

.app-container.theme-light .chat-avatar {
	box-shadow: 0 4rpx 12rpx rgba(139, 92, 246, 0.2);
}

.avatar-text {
	font-size: 36rpx;
	filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.3));
}

.favorite-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	min-width: 0;
}

.favorite-header {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 16rpx;
}

.favorite-title {
	flex: 1;
	font-size: 34rpx;
	font-weight: 700;
	color: #ffffff;
	line-height: 1.3;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.app-container.theme-light .favorite-title {
	color: #1f2937;
	text-shadow: none;
}

.favorite-badge {
	flex-shrink: 0;
	padding: 8rpx 16rpx;
	background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
	color: #ffffff;
	font-size: 20rpx;
	font-weight: 600;
	border-radius: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(245, 158, 11, 0.3);
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

.favorite-preview {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.85);
	line-height: 1.5;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	line-clamp: 2;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
	margin-bottom: 8rpx;
}

.app-container.theme-light .favorite-preview {
	color: #6b7280;
	text-shadow: none;
}

.favorite-footer {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 16rpx;
}

.favorite-time {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.6);
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

.app-container.theme-light .favorite-time {
	color: #9ca3af;
	text-shadow: none;
}

.continue-chat {
	font-size: 24rpx;
	color: #06b6d4;
	font-weight: 600;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
	animation: pulse 2s infinite;
}

.app-container.theme-light .continue-chat {
	color: #0891b2;
	text-shadow: none;
}

@keyframes pulse {
	0%, 100% { opacity: 1; }
	50% { opacity: 0.7; }
}

.favorite-actions {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	flex-shrink: 0;
}

.unfavorite-btn {
	width: 72rpx;
	height: 72rpx;
	border-radius: 50%;
	background: rgba(239, 68, 68, 0.2);
	border: 2rpx solid rgba(239, 68, 68, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
	cursor: pointer;
	backdrop-filter: blur(10rpx);
}

.unfavorite-btn:hover {
	background: rgba(239, 68, 68, 0.8);
	transform: scale(1.1);
	box-shadow: 0 4rpx 16rpx rgba(239, 68, 68, 0.4);
}

.unfavorite-icon {
	font-size: 32rpx;
	filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.3));
}

.empty-favorites {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 60rpx;
	text-align: center;
	animation: fadeIn 0.6s ease-in-out;
}

@keyframes fadeIn {
	from { opacity: 0; transform: translateY(40rpx); }
	to { opacity: 1; transform: translateY(0); }
}

.empty-icon-wrapper {
	position: relative;
	margin-bottom: 40rpx;
}

.empty-icon {
	font-size: 160rpx;
	opacity: 0.8;
	animation: float 3s ease-in-out infinite;
	filter: drop-shadow(0 4rpx 12rpx rgba(0, 0, 0, 0.2));
}

@keyframes float {
	0%, 100% { transform: translateY(0); }
	50% { transform: translateY(-10rpx); }
}

.empty-shine {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	width: 40rpx;
	height: 40rpx;
	background: radial-gradient(circle, rgba(255, 255, 255, 0.8) 0%, transparent 70%);
	border-radius: 50%;
	animation: shine 2s ease-in-out infinite;
}

@keyframes shine {
	0%, 100% { opacity: 0; transform: scale(0.5); }
	50% { opacity: 1; transform: scale(1); }
}

.empty-text {
	font-size: 40rpx;
	font-weight: 700;
	color: #ffffff;
	margin-bottom: 40rpx;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
	animation: slideInUp 0.8s ease-in-out 0.2s both;
}

@keyframes slideInUp {
	from { opacity: 0; transform: translateY(30rpx); }
	to { opacity: 1; transform: translateY(0); }
}

.app-container.theme-light .empty-text {
	color: #1f2937;
	text-shadow: none;
}

.empty-action {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 20rpx 32rpx;
	background: linear-gradient(135deg, #8b5cf6 0%, #06b6d4 100%);
	border-radius: 50rpx;
	transition: all 0.3s ease;
	cursor: pointer;
	box-shadow: 0 4rpx 16rpx rgba(139, 92, 246, 0.3);
	animation: slideInUp 0.8s ease-in-out 0.6s both;
}

.empty-action:hover {
	transform: translateY(-2rpx) scale(1.05);
	box-shadow: 0 8rpx 24rpx rgba(139, 92, 246, 0.4);
}

.action-text {
	font-size: 28rpx;
	font-weight: 600;
	color: #ffffff;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

.action-arrow {
	font-size: 24rpx;
	font-weight: bold;
	color: #ffffff;
	transition: transform 0.3s ease;
}

.empty-action:hover .action-arrow {
	transform: translateX(4rpx);
}
</style>
